package com.jcfk.system.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jcfk.common.business.service.BaseService;
import com.jcfk.common.core.utils.BeanUtils;
import com.jcfk.common.security.utils.SecurityUtils;
import com.jcfk.system.dao.RefUserOrganizationMappingDao;
import com.jcfk.system.domain.dto.RefUserOrganizationMappingDTO;
import com.jcfk.system.domain.dto.SysOrganizationDTO;
import com.jcfk.system.domain.dto.SysPermissionDTO;
import com.jcfk.system.domain.dto.SysUserDTO;
import com.jcfk.system.domain.po.RefUserOrganizationMapping;
import com.jcfk.system.domain.po.SysOrganization;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.jcfk.common.core.utils.BeanUtils.convertList;

@Service
public class RefUserOrganizationMappingService extends BaseService<RefUserOrganizationMappingDao, RefUserOrganizationMapping> {

    @Autowired
    private SysOrganizationService sysOrganizationService;
    @Autowired
    private SysUserService SysUserService;

    /**
     * 添加组织机构
     *
     * @param mapping 添加对象
     */
    public void insert(RefUserOrganizationMappingDTO mapping) {

        QueryWrapper<RefUserOrganizationMapping> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(RefUserOrganizationMapping::getUserId, mapping.getUserId());
        this.remove(queryWrapper);

        List<RefUserOrganizationMapping> list = new ArrayList<>();
        for (String organizationId : mapping.getOrganizationIds()) {
            RefUserOrganizationMapping refUserOrganizationMapping = new RefUserOrganizationMapping();
            refUserOrganizationMapping.setUserId(mapping.getUserId());
            refUserOrganizationMapping.setOrganizationId(organizationId);
            list.add(refUserOrganizationMapping);
        }

        if (list.size() > 0) this.saveBatch(list);
    }

    /**
     * 编辑组织机构
     *
     * @param mapping 添加对象
     */
    public void update(RefUserOrganizationMappingDTO mapping) {
        RefUserOrganizationMapping refUserOrganizationMapping = this.getById(mapping);
        BeanUtils.copyProperties(mapping, refUserOrganizationMapping);
        this.save(refUserOrganizationMapping);
    }


    /**
     * 设置添加默认值
     *
     * @param item 添加对象
     */
    public void setDefaultValue(RefUserOrganizationMapping item) {
        if (StrUtil.isEmpty(item.getCreatedUserId())) {
            item.setCreatedUserId(SecurityUtils.getUserId());
            item.setCreateTime(new Date());
        }
        item.setLastUpdatedUserId(SecurityUtils.getUserId());
        item.setLastUpdateTime(new Date());

    }

    /**
     * 获取当前用户组织机构
     *
     * @param userId
     */
    public List<SysOrganizationDTO> getUserOrganList(String userId) {
        return this.getUserOrganList(userId,null);
    }

    /**
     * 获取当前用户指定类型组织机构
     *
     * @param userId
     */
    public List<SysOrganizationDTO> getUserOrganList(String userId,String organizationType) {
        SysUserDTO sysUserDTO = SysUserService.get(userId);
        if ("superadmin".equals(sysUserDTO.getUserType())) {
            QueryWrapper<SysOrganization> sysOrganizationQueryWrapper = new QueryWrapper<>();
            sysOrganizationQueryWrapper.lambda().eq(SysOrganization::getDeleted, 0);
            if(!StrUtil.isEmpty(organizationType)){
                sysOrganizationQueryWrapper.lambda().eq(SysOrganization::getOrganizationType, 3);
            }
            sysOrganizationQueryWrapper.lambda().orderByAsc(SysOrganization::getSort);
            List<SysOrganization> list = sysOrganizationService.list(sysOrganizationQueryWrapper);
            List<SysOrganizationDTO> dtos = convertList(list, SysOrganizationDTO.class);
            return dtos;
        } else {
            QueryWrapper<RefUserOrganizationMapping> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(RefUserOrganizationMapping::getUserId, userId);

            List<String> ids = super.list(queryWrapper).stream().map(RefUserOrganizationMapping::getOrganizationId).collect(Collectors.toList());

//            if (sysUserDTO != null && sysUserDTO.getDepartmentId() != null && !"".equals(sysUserDTO.getDepartmentId()))
//                ids.add(sysUserDTO.getDepartmentId());
//
//            if (sysUserDTO != null && sysUserDTO.getOrganizationId() != null && !"".equals(sysUserDTO.getOrganizationId()))
//                ids.add(sysUserDTO.getOrganizationId());

            SysOrganizationDTO organization=sysOrganizationService.get(sysUserDTO.getOrganizationId());
            String[] organizationIds=organization.getAllId().split(",");
            for(String organizationId : organizationIds){
                ids.add(organizationId);
            }

            if (ids.size() > 0) {
                QueryWrapper<SysOrganization> sysOrganizationQueryWrapper = new QueryWrapper<>();
                sysOrganizationQueryWrapper.lambda().in(SysOrganization::getId, ids);
                sysOrganizationQueryWrapper.lambda().eq(SysOrganization::getDeleted, 0);
                sysOrganizationQueryWrapper.lambda().orderByAsc(SysOrganization::getSort);
                if(!StrUtil.isEmpty(organizationType)){
                    sysOrganizationQueryWrapper.lambda().eq(SysOrganization::getOrganizationType, 3);
                }
                List<SysOrganization> list = sysOrganizationService.list(sysOrganizationQueryWrapper);
                List<SysOrganizationDTO> dtos = convertList(list, SysOrganizationDTO.class);
                return dtos;
            }
        }
        return new ArrayList<>();
    }

    /**
     * 获取当前用户工厂
     *
     * @param userId
     */
    public List<SysOrganizationDTO> getUserOrgansTypeOfFactory(String userId) {
        return this.getUserOrganList(userId,"3");
    }

    public List<RefUserOrganizationMappingDTO> getUserOrganization(String userId) {
        if (StrUtil.isEmpty(userId)) return new ArrayList<>();
        List<RefUserOrganizationMapping> list = this.list(Wrappers.<RefUserOrganizationMapping>lambdaQuery()
            .eq(RefUserOrganizationMapping::getUserId, userId));
        return convertList(list, RefUserOrganizationMappingDTO.class);
    }
}
